//
//  LoanPageViewController.m
//  LoanTeam15
//
//  Created by gynjobs on 2017/8/22.
//  Copyright © 2017年 cangming. All rights reserved.
//

#import "LoanPageViewController.h"
#import "SelectionTableCell.h"
#import "inputTextFTableViewCell.h"
#import "RadioTableViewCell.h"
#import "SmsTableViewCell.h"
#import "TextUnitTableView.h"
#import "PickerViewController.h"
#import "LoanSuccessViewController.h"
#import "GetCityLocationViewController.h"
#import "LoanMainTopView.h"
//#import "ThirdPartyManager.h"
#import "NotificationCenterManager.h"
#import "LoginViewController.h"
#import "LoginMainAction.h"
#import "NetWorkManager.h"
#import "loanTableViewHeadView.h"
@interface LoanPageViewController ()<UITableViewDataSource,UITableViewDelegate,BaseDataViewClollBack,inputTextFTableViewCellDelegate,RadioTableViewCellDelegate,SmsTableViewCellDelegate>
@property(strong,nonatomic)loanTableViewHeadView *headView;
@property(strong,nonatomic)UITableView *backTableView;
@end

@implementation LoanPageViewController

-(instancetype)init{
    
    if(self = [super init]){
        
        _loanActioin = [[LoanMainAction alloc] init];
    }
    
    return self;
    
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}


-(void)loadView{
    [super loadView];
    
    _mainView = [[LoanMainView alloc] init];
    self.view = _mainView;
    
    self.navigationController.interactivePopGestureRecognizer.delegate = (id)self;
}

-(void)viewDidLoad{
    
    [super viewDidLoad];
    self.title = @"贷款";
    //      _loanActioin = [[LoanMainAction alloc] init];
    [_loanActioin addObserver:self forKeyPath:@"score" options:NSKeyValueObservingOptionNew context:nil];
    
    //    [self addTabelViewForView];
    //    [self addHeadViewForView];
    _mainView.inputTableView.delegate = self;
    _mainView.inputTableView.dataSource = self;
    _mainView.inputTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_mainView setTableViewFooter];
    [_mainView.nextBtn addTarget:self action:@selector(nextBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    _loanActioin.mainTableView = _mainView.inputTableView;
    [_mainView.processView setProcess:_loanActioin.step -1];
    
    [_loanActioin
     start];
    [self setLeftBackButton];
}
-(void)setLeftBackButton{
    UIImageView *backButton = [self setLeftNavigationButtonIconName:@"返回icon" AndSize:CGSizeMake(40, 60)];
    backButton.contentMode = UIViewContentModeCenter ;
    UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(skidClick:)];
    [backButton addGestureRecognizer:tapGes];
}
-(void)skidClick:(UITapGestureRecognizer *)tapGes{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)addHeadViewForView{
    loanTableViewHeadView *headView = [[loanTableViewHeadView alloc]init];
    [self.view addSubview:headView];
    self.headView = headView;
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left);
        make.top.equalTo(self.view.mas_top);
        make.height.mas_equalTo(R_Y_H(300));
        make.width.mas_equalTo(WINSIZEWIDTH);
    }];
}
#pragma mark ---tableView---
-(void)addTabelViewForView{
    self.backTableView = [[UITableView alloc]init];
    self.backTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.backTableView];
    //    [self.backTableView mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.left.equalTo(self.view.mas_left);
    //        make.top.equalTo(self.headView.mas_bottom);
    //        make.right.equalTo(self.view.mas_right);
    //        make.bottom.equalTo(self.view.mas_bottom);
    //    }];
    self.backTableView.frame = CGRectMake(0, 0, WINSIZEWIDTH, WINSIZEHEIGHT-64);
    self.backTableView.delegate = self;
    self.backTableView.dataSource = self;
    //    [self addFootViewForTableView];
}
//-(void)addFootViewForTableView{
//    centerButtonView *centerButton = [[centerButtonView alloc]init];
//    centerButton.backgroundColor = [UIColor orangeColor];
//    [self.backTableView setTableFooterView:centerButton];
//    centerButton.frame = CGRectMake(0, 0, WINSIZEWIDTH, R_Y_H(164));
//
//}



-(void)dealloc{
    
    [_loanActioin removeObserver:self forKeyPath:@"score"];
}

-(void)setBackBtn{
    //  to nothing
}


#pragma mark -
#pragma mark loanaction kvo
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    if([keyPath isEqualToString:@"score"]){
        
        NSString * scoreStr = [change valueForKey:@"new"];
        _mainView.processView.successLabel.text = [NSString stringWithFormat:@"贷款申请成功率提高%@%%",scoreStr];
        
    }
    
}




#pragma mark -
#pragma mark tableview datasource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    GYNLog(@"%ld",(long)[_loanActioin getSectionCount]);
    return [_loanActioin getSectionCount];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return [_loanActioin getRowCount:section];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    DataModle * item = [_loanActioin rowData:[indexPath section] withRow:[indexPath row]];
    
    switch (item.type) {
            
            
        case DATA_TYPE_RADIO:{
            
            RadioTableViewCell * radioCell = [tableView dequeueReusableCellWithIdentifier:RADIO_CELL_ID];
            
            if(!radioCell){
                
                radioCell = [[RadioTableViewCell alloc] init];
            }
            
            radioCell.isExpand = item.extend;
            radioCell.titleLabel.text = item.name;
            radioCell.radioDelegate = self;
            radioCell.item = item;
            
            id dataDic = [[_loanActioin cacheData] valueForKey:item.key];
            if(dataDic){
                
                [radioCell setRadioSelected:[[dataDic valueForKey:@"data"] integerValue]];
                
            }else{
                
                [radioCell setRadioSelected:-1];
            }
            
            return radioCell;
            
            break;
        }
            
        case DATA_TYPE_TEXT:
        case DATA_TYPE_NUM:
        case DATA_TYPE_PHONE:
            
        {
            inputTextFTableViewCell *textFieldCell = [tableView dequeueReusableCellWithIdentifier:TEXT_FIELD_CELL_ID];
            if(!textFieldCell){
                
                textFieldCell = [[inputTextFTableViewCell alloc] init];
                
            }
            textFieldCell.isExpand = item.extend;
            textFieldCell.textDelegate = self;
            textFieldCell.item = item;
            
            textFieldCell.titleLabel.text = item.name;
            textFieldCell.contentTextfield.placeholder = item.tip2;
            
            NSString * content = @"";
            id dataDic = [[_loanActioin cacheData] valueForKey:item.key];
            
            if(dataDic){
                content = [dataDic valueForKey:@"data"];
            }
            
            textFieldCell.contentTextfield.text = content;
            
            return textFieldCell;
            
            break;
        }
        case DATA_TYPE_CITY:
        case DATA_TYPE_LIST:{
            SelectionTableCell * selectionCell = [tableView dequeueReusableCellWithIdentifier:SELECTION_CELL_ID];
            if(!selectionCell){
                
                selectionCell = [[SelectionTableCell alloc] init];
                
            }
            
            selectionCell.isExpand = item.extend;
            selectionCell.titleLabel.text = item.name;
            selectionCell.contentTextFiled.placeholder = item.tip2;
            NSString * content = @"";
            id dataDic = [[_loanActioin cacheData] valueForKey:item.key];
            
            if(dataDic){
                content = [dataDic valueForKey:@"data"];
            }
            
            selectionCell.contentTextFiled.text = content;
            
            return selectionCell;
            
            break;
        }
            
        case DATA_TYPE_SMS:{
            SmsTableViewCell * smsCell = [tableView dequeueReusableCellWithIdentifier:SMS_CELL_ID];
            if(!smsCell){
                
                smsCell = [[SmsTableViewCell alloc] init];
            }
            
            smsCell.smsDelegate = self;
            smsCell.textDelegate = self;
            smsCell.item = item;
            smsCell.titleLabel.text = item.name;
            smsCell.contentTextfield.placeholder = item.tip2;
            return smsCell;
            
            
            
            break;
        }
            
        case DATA_TYPE_UNIT:{
            TextUnitTableView * unitCell = [tableView dequeueReusableCellWithIdentifier:TEXT_UNIT_CELL_ID];
            if(!unitCell){
                unitCell = [[TextUnitTableView alloc] init];
            }
            
            unitCell.textDelegate = self;
            unitCell.item = item;
            unitCell.isExpand = item.extend;
            unitCell.titleLabel.text = item.name;
            unitCell.contentTextfield.placeholder = item.tip2;
            unitCell.unitLabel.text = item.tip1;
            NSString * content = @"";
            id dataDic = [[_loanActioin cacheData] valueForKey:item.key];
            
            if(dataDic){
                content = [dataDic valueForKey:@"data"];
            }
            unitCell.contentTextfield.text = content;
            
            
            return unitCell;
            break;
        }
            
        default:
            break;
    }
    
    return nil;
    
}



#pragma mark -
#pragma mark tableview delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return LOAN_BASE_CELL_HEIGHT;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if(section == [_loanActioin getSectionCount] -1 && [_loanActioin step] != 1){
        
        return 0;
    }
    
    return LOAN_BASE_SECTION_HEADER_HEIGHT;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * view = [_mainView genSectionHeaderView];
    //    UIView *view = [[UIView alloc]init];
    //    view.frame =CGRectMake(0, 0, 320, 120);
    return view;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    DataModle * item = [_loanActioin rowData:[indexPath section] withRow:[indexPath row]];
    
    if(item.type == DATA_TYPE_CITY){
        GetCityLocationViewController * cityController = [[GetCityLocationViewController alloc] init];
        cityController.itemData = item;
        cityController.delegate = self;
        cityController.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:cityController animated:YES];
        return;
        
    }
    
    
    if(item.type != DATA_TYPE_LIST){
        
        return;
    }
    
    PickerViewController * controller = [[PickerViewController alloc] init];
    controller.itemData = item;
    controller.delegate = self;
    
    self.definesPresentationContext = YES;
    controller.modalPresentationStyle = UIModalPresentationOverCurrentContext;
    [self presentViewController:controller animated:YES completion:^{
        [UIView animateWithDuration:0.2 animations:^{
            
            controller.view.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:.2];
        }];
        
    }];
    
}


#pragma mark -
#pragma mark next btn pressed
-(void)nextBtnPressed:(id)sender{
    
    [self.view endEditing:YES];
    if(_loanActioin.step == 1){
        
        [LoadingAnimalView showWhiteLoadingAddedTo:self.view];
        
        __weak typeof(self) weakself = self;
        [_loanActioin commit:nil withCallBack:^(id error_msg){
            if(!error_msg){
                //                [TalkingData trackEvent:@"贷款信息填写成功，进入下一步" label:[APP_NO stringValue]];
                if ([LoginMainAction isLogin]) {
                    [weakself successAdvance];
                }else{
                    NSDictionary *dic = [_loanActioin genCommitDic];
                    [LoginMainAction quickLoginWithUserName:dic[@"mobile"] withCallBlock:^(id error_msg) {
                        if (!error_msg) {
                            [weakself successAdvance];
                        }else{
                            [weakself errorWithMessage:error_msg];
                        }
                    }];
                }
                
                
            }else{
                [weakself errorWithMessage:error_msg];
            }
            
            
        }];
        
        
        
    }else{
        [LoadingAnimalView showWhiteLoadingAddedTo:self.view];
        [_loanActioin commit:nil withCallBack:^(id error_msg){
            
            [LoadingAnimalView hideLoadingForView:self.view];
            if(!error_msg){
                //                [TalkingData trackEvent:@"贷款个人信息填写成功，申请完成" label:[APP_NO stringValue]];
                //                [[ThirdPartyManager getInstance] logUmengEvent:U_loanProcess_step2];
                
                self.hidesBottomBarWhenPushed = YES;
                LoanSuccessViewController * successController = [[LoanSuccessViewController alloc] init];
                successController.score = _loanActioin.score;
                [self.navigationController pushViewController:successController animated:YES];
                
            }else{
                
                [LoadingAnimalView showToastAddedTo:self.view withTitle:error_msg withBlock:nil];
                
            }
            
            
        }];
        
        
    }
    
}


- (void)successAdvance{
    [LoadingAnimalView hideLoadingForView:self.view];
    
    //    [[ThirdPartyManager getInstance] logUmengEvent:U_loanProcess_step1];
    LoanPageViewController * nextController = [[LoanPageViewController alloc] init];
    nextController.loanActioin.type = _loanActioin.type;
    nextController.loanActioin.step = _loanActioin.step + 1 ;
    nextController.loanActioin.preScore = _loanActioin.score;
    nextController.loanActioin.stepDic1 = [_loanActioin genCommitDic];
    
    self.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:nextController animated:YES];
    [NotificationCenterManager  sendNotification:LOAN_STEP1_NEXT_NOTIFICATION];
}

- (void)errorWithMessage:(NSString *)errorMsg{
    [LoadingAnimalView hideLoadingForView:self.view];
    [LoadingAnimalView showToastAddedTo:self.view withTitle:errorMsg withBlock:nil];
    
}


#pragma mark -
#pragma mark callback delegate

-(void)callBackData:(id)dic{
    
    // commit data
    NSString * key = [dic valueForKey:@"key"];
    NSString * data = [dic valueForKey:@"data"];
    NSString * score = [dic valueForKey:@"score"];
    id cid = [dic valueForKey:@"id"];
    NSMutableDictionary * fdic = [[NSMutableDictionary alloc] initWithCapacity:3];
    [fdic setValue:data forKey:@"data"];
    
    if(cid){
        
        [fdic setValue:cid forKey:@"id"];
    }
    
    if(score){
        
        [fdic setValue:score forKey:@"score"];
    }
    
    [_loanActioin setCommitItem:fdic withKey:key];
    [_mainView.inputTableView reloadData];
    
}

#pragma mark -
#pragma mark loan text delegate

-(void)loanTextField:(UITextField*)textFiled withData:(id) dic {
    
    // commit data
    NSString * key = [dic valueForKey:@"key"];
    NSString * data = [dic valueForKey:@"data"];
    NSString * score = [dic valueForKey:@"score"];
    id cid = [dic valueForKey:@"id"];
    NSMutableDictionary * fdic = [[NSMutableDictionary alloc] initWithCapacity:3];
    [fdic setValue:data forKey:@"data"];
    
    if(cid){
        
        [fdic setValue:cid forKey:@"id"];
    }
    
    if(score){
        
        [fdic setValue:score forKey:@"score"];
    }
    
    [_loanActioin setCommitItem:fdic withKey:key];
    
    
}

#pragma mark -
#pragma mark loan radio cell delegate

-(void)loanRadioCell:(RadioTableViewCell*)radioCell withData:(id)dic{
    
    NSString * key = [dic valueForKey:@"key"];
    NSString * data = [dic valueForKey:@"data"];
    NSString * score = [dic valueForKey:@"score"];
    
    NSMutableDictionary * fdic = [[NSMutableDictionary alloc] initWithCapacity:3];
    [fdic setValue:data forKey:@"data"];
    [fdic setValue:score forKey:@"score"];
    
    [_loanActioin setCommitItem:fdic withKey:key];
    
    [_mainView.inputTableView reloadData];
}


#pragma mark -
#pragma mark loan sms cell delegate
-(void)loanSmsCell:(SmsTableViewCell*)cell withCallBack:(void (^)(BOOL,id))smsCallBack{
    
    BOOL isMobile = [_loanActioin isMobile];
    __weak typeof(self) weakself = self;
    
    if (!isMobile) {
        [LoadingAnimalView showToastAddedTo:self.view withTitle:@"请输入正确的手机号" withBlock:nil];
        return;
    }
    //    if (isMobile) {
    [LoadingAnimalView showWhiteLoadingAddedTo:self.view];
    [_loanActioin getSmsCode:^(id error_msg) {
        [LoadingAnimalView hideLoadingForView:weakself.view];
        if(error_msg){
            
            [self showToastAddWithTitle:error_msg];
            smsCallBack(NO,error_msg);
        }else{
            [LoadingAnimalView showToastAddedTo:weakself.view withTitle:@"验证码已发送" withBlock:^{
                smsCallBack(YES,error_msg);
            }];
        }
    }];
    //    }
    //    smsCallBack(isMobile,nil);
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
